﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ExcelFileQueryTool
{
    public partial class frmClientSalesList : Form
    {
        BillSalesService _salesService = new BillSalesService(AppConfig.DBConnectionString);
        CrmPeopleService _peopleService = new CrmPeopleService(AppConfig.DBConnectionString);
        private SortableBindingList<BillSales> _currentSource = null;
        private static string[] HIDE_COLUMNS = { "ClientId", "ClientName", "ProductId", "TotalMoney", "Status", "CreatedTime", "LastUpdatedTime", "Note", "IsPaidOff", "BillType" };
        private IList<KeyValuePair<int, string>> _modifiedBillNO = new List<KeyValuePair<int, string>>();
        private IList<int> _modifiedSalesId = new List<int>();
        private const string DATE_FORMAT = "yyyy/M/d";

        /// <summary>
        /// 判断当前的单元格值是否正在变更的标识，如果是正在变更过程，就不再执行该事件(非线程安全设计)
        /// </summary>
        /// <remarks>这个设计只能处理单个变更，如果需要处理多个变更，可使用盏的方式实现</remarks>
        private bool _cellValueChanging = false;

        public frmClientSalesList()
        {
            InitializeComponent();

            cboxHasBillNumber.SelectedItem = "所有";
            btnSaveAll.Enabled = false;
        }

        private void InitClientNameSearchAutoCompleteSource()
        {
            if (txtClientNameSearch.AutoCompleteCustomSource.Count > 0)
                return;

            // maybe use async worker
            var clientList = _peopleService.QueryList(null, null, null);
            if (clientList != null)
            {
                txtClientNameSearch.AutoCompleteCustomSource.AddRange(clientList.Select(x => x.Name).ToArray());
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DoSearch();
        }

        private void DoSearch()
        {
            string clientName = txtClientNameSearch.Text.Trim();
            if (string.IsNullOrEmpty(clientName))
            {
                //MessageBox.Show("请指定待查询交易记录的客户名称", "提示");
                MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户销售记录查询列表",
                                Content = "请指定待查询交易记录的客户名称"
                            });
                return;
            }

            cboxHasBillNumber.SelectedItem = "所有";

            DateTime sales_date_begin = SqlDateTime.MinValue.Value;
            DateTime sales_date_end = SqlDateTime.MaxValue.Value;

            string sales_date_begin_str = txtSalesDateBegin.Text.Trim();
            string sales_date_end_str = txtSalesDateEnd.Text.Trim();

            if (string.IsNullOrEmpty(sales_date_begin_str) == false)
            {
                if (DateTime.TryParse(sales_date_begin_str, out sales_date_begin) == false)
                    //MessageBox.Show("无效的日期格式[销售日期起]", "提示");
                    MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户销售记录查询列表",
                                Content = "无效的日期格式[销售日期起]"
                            });
            }

            if (string.IsNullOrEmpty(sales_date_end_str) == false)
            {
                if (DateTime.TryParse(sales_date_end_str, out sales_date_end) == false)
                    //MessageBox.Show("无效的日期格式[销售日期止]", "提示");
                    MessageDispatcherManager.DispatchMessage(
                                new AppMessage
                                {
                                    Time = DateTime.Now,
                                    Level = AppMessageLevel.Info,
                                    Title = "客户销售记录查询列表",
                                    Content = "无效的日期格式[销售日期止]"
                                });
            }

            var list = _salesService.GetListByClientName(
                                            clientName,
                                            sales_date_begin == SqlDateTime.MinValue.Value ? null : new Nullable<DateTime>(sales_date_begin),
                                            sales_date_end == SqlDateTime.MaxValue.Value ? null : new Nullable<DateTime>(sales_date_end));

            if (list != null)
                _currentSource = new SortableBindingList<BillSales>(list.ToList());
            else
                _currentSource = null;


            dgvData.DataSource = _currentSource;

            // 刷新了数据，需要清空之前对列表数据的修改
            _modifiedBillNO.Clear();
            _modifiedSalesId.Clear();

            btnSaveAll.Enabled = false;
            _cellValueChanging = false;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cboxHasBillNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dgvData.DataSource == null)
                return;

            switch ((string)cboxHasBillNumber.SelectedItem)
            {
                case "无单号":
                    {
                        var list = _currentSource.Where(x => string.IsNullOrEmpty(x.BillNumber)).ToList<BillSales>();
                        dgvData.DataSource = new SortableBindingList<BillSales>(list);
                        break;
                    }

                case "有单号":
                    {
                        var list = _currentSource.Where(x => string.IsNullOrEmpty(x.BillNumber) == false).ToList<BillSales>();
                        dgvData.DataSource = new SortableBindingList<BillSales>(list);
                        break;
                    }

                default:
                    dgvData.DataSource = _currentSource;
                    break;
            }
        }

        private void btnBillNumberMgnt_Click(object sender, EventArgs e)
        {
            if (dgvData.Columns.Count > 0)
            {
                foreach (var col in HIDE_COLUMNS)
                {
                    dgvData.Columns[col].Visible = btnBillNumberMgnt.Checked;
                }
            }

            btnSaveBillNO.Visible = btnBillNumberMgnt.Checked;
            btnSaveAll.Enabled = !btnBillNumberMgnt.Checked;
            btnDelete.Enabled = !btnBillNumberMgnt.Checked;
        }

        private void dgvData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (_cellValueChanging)
            {
                _cellValueChanging = false;
                return;
            }

            if (btnBillNumberMgnt.Checked) // 单号管理模式
            {
                if (dgvData.Columns[e.ColumnIndex].Name == "BillNumber")
                {
                    var billNO = (string)dgvData[e.ColumnIndex, e.RowIndex].Value;

                    if (billNO != null && billNO.Length > 50)
                    {
                        //MessageBox.Show("超出单号最大长度，请重新填写！若不修改，则放弃该单号的保存操作！", "提示");
                        MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "单号管理",
                                Content = "超出单号最大长度，请重新填写！若不修改，则放弃该单号的保存操作！"
                            });
                        return;
                    }

                    var id = (int)dgvData["Id", e.RowIndex].Value;
                    _modifiedBillNO.Add(new KeyValuePair<int, string>(id, billNO));
                }
            }
            else // 普通修改模式
            {
                var id = (int)dgvData["Id", e.RowIndex].Value;
                if (_modifiedSalesId.Contains(id) == false)
                    _modifiedSalesId.Add(id);

                try
                {
                    btnSaveAll.Enabled = true;

                    switch (dgvData.Columns[e.ColumnIndex].Name)
                    {
                        case "ClientId":
                            {
                                var newClientId = Convert.ToInt32(dgvData[e.ColumnIndex, e.RowIndex].Value);
                                if (newClientId != 0)
                                {
                                    _cellValueChanging = true;
                                    var people = _peopleService.GetById(newClientId);
                                    if (people != null)
                                        dgvData["ClientName", e.RowIndex].Value = people.Name;
                                    else
                                        dgvData["ClientId", e.RowIndex].Value = 0; // 客户ID不存在，设置为0
                                }
                                break;
                            }
                        case "ClientName":
                            {
                                var newClientName = dgvData[e.ColumnIndex, e.RowIndex].Value.ToString();
                                if (string.IsNullOrEmpty(newClientName) == false)
                                {
                                    _cellValueChanging = true;
                                    var people = _peopleService.GetByName(newClientName);
                                    if (people != null)
                                        dgvData["ClientId", e.RowIndex].Value = people.Id.Value;
                                    else
                                        dgvData["ClientId", e.RowIndex].Value = 0;
                                }
                                break;
                            }
                        case "ProductPrice":
                        case "ProductAmount":
                        case "LoadingFee":
                        case "ShippingFee":
                            {
                                var price = Convert.ToDecimal(dgvData["ProductPrice", e.RowIndex].Value);
                                var amount = Convert.ToDecimal(dgvData["ProductAmount", e.RowIndex].Value);
                                var loadingFee = Convert.ToDecimal(dgvData["LoadingFee", e.RowIndex].Value);
                                var shippingFee = Convert.ToDecimal(dgvData["ShippingFee", e.RowIndex].Value);
                                dgvData["TotalMoney", e.RowIndex].Value = amount * price + loadingFee + shippingFee;
                                _cellValueChanging = true;
                                break;
                            }
                        default:
                            break;
                    }
                }
                catch
                {
                    // ignore this exception
                }
            }
        }

        private void btnSaveBillNO_Click(object sender, EventArgs e)
        {
            if (_modifiedBillNO.Count > 0)
            {
                _salesService.UpdateBillNumber(_modifiedBillNO);

                _modifiedBillNO.Clear();
            }
        }

        private void btnSaveAll_Click(object sender, EventArgs e)
        {
            if (_modifiedSalesId.Count > 0)
            {
                foreach (var item in (IEnumerable<BillSales>)dgvData.DataSource)
                {
                    if (_modifiedSalesId.Contains(item.Id.Value))
                        _salesService.Update(item);
                }

                _modifiedSalesId.Clear();
                _cellValueChanging = false;

                //MessageBox.Show("保存成功！", "提示");
                MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户销售记录管理",
                                Content = "保存成功！"
                            });
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            var selected = dgvData.SelectedRows;
            if (selected == null || selected.Count == 0)
                return;

            var result = MessageBox.Show("是否永久删除选定的数据？(是则直接删除，否则标记为删除)", "提示", MessageBoxButtons.YesNo);
            var fake_del = result == System.Windows.Forms.DialogResult.No;

            foreach (DataGridViewRow r in selected)
            {
                _salesService.Delete((int)r.Cells["Id"].Value, fake_del);
            }

            DoSearch();
        }

        private void txtSalesDateBegin_Click(object sender, EventArgs e)
        {
            var p = toolSalesList.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
            var f = new frmDatePicker(p, null);
            f.DateSelected += (ss, ee) => { txtSalesDateBegin.Text = ee.Date.ToString(DATE_FORMAT); };
            f.Show();
        }

        private void txtSalesDateEnd_Click(object sender, EventArgs e)
        {
            var p = toolSalesList.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y));
            var f = new frmDatePicker(p, null);
            f.DateSelected += (ss, ee) => { txtSalesDateEnd.Text = ee.Date.ToString(DATE_FORMAT); };
            f.Show();
        }

        private void txtClientNameSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == (int)Keys.Enter)
                DoSearch();
        }

        private void txtClientNameSearch_Enter(object sender, EventArgs e)
        {
            InitClientNameSearchAutoCompleteSource();
        }
    }
}
